
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from initialization.dbInit import get_db_session
from fastapi import Request, Depends, HTTPException
from model.entitys import BackApi, RoleBackApi, UserRole
from utils.tokenUtil import analysis_token, verify_token_format

async def permission_verification(request: Request, session: AsyncSession = Depends(get_db_session)):
    token_str_list = await verify_token_format(request.headers.get("Authorization", None))
    payload = await analysis_token(token_str_list[1])

    backApiList = (await session.execute(select(BackApi).distinct(). \
                                      join(RoleBackApi, RoleBackApi.BackApiId == BackApi.id). \
                                      join(UserRole, UserRole.roleId == RoleBackApi.roleId). \
                                      where(UserRole.userId == payload["sub"]))).scalars().all()

    exist = False
    for ba in backApiList:
        if ba.path == request.url.path and ba.method == request.method.lower():
            exist = True
            break

    if exist is False:
        raise HTTPException(status_code=403, detail="无权访问该接口")














